package com.sikaryofficial.backend.manager.information;

import cn.hutool.core.text.CharSequenceUtil;
import com.sikaryofficial.backend.domain.dto.resp.information.ArticleWordImportDTO;
import com.sikaryofficial.backend.domain.vo.ImportArticleContentVO;
import com.sikaryofficial.backend.utils.WordProcessUtil;
import com.sikaryofficial.system.api.model.att.AttachmentResp;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.MessageFormat;
import java.util.List;

/**
 * @author : qinjinyuan
 * @desc : 文章word数据导入
 * @date : 2024/04/25 14:59
 */
@Component
@Slf4j
public class WordAnalysisManager {
    private static final String IMG_TAG = "<img>src=\"{0}\"</img>";
    private static final String BR_TAG = "<br/>";
    @SneakyThrows
    public ArticleWordImportDTO wordAnalysis(MultipartFile multipartFile) {
        List<ImportArticleContentVO> contentVOList = WordProcessUtil.wordAnalysis(multipartFile);
        return buildContent(contentVOList);
    }

    private ArticleWordImportDTO buildContent(List<ImportArticleContentVO> contentVOList) {
        ArticleWordImportDTO articleWordImport = new ArticleWordImportDTO();
        StringBuilder sb = new StringBuilder();
        List<AttachmentResp> attachmentList = Lists.newArrayList();
        int i = 0;
        for (ImportArticleContentVO contentVO : contentVOList) {
            if (CharSequenceUtil.isBlank(contentVO.getContent())) {
                continue;
            }
            String content = contentVO.getContent();
            if (contentVO.getType().equals(1)) {
                content = MessageFormat.format(IMG_TAG, contentVO.getContent());
                attachmentList.add(AttachmentResp.builder()
                        .url(contentVO.getContent())
                        .hasCover(i == 0 ? 1 : 0)
                        .build());
                i++;
            }
            sb.append(content).append(BR_TAG);
        }
        articleWordImport.setAttachmentList(attachmentList);
        articleWordImport.setContent(sb.toString());
        return articleWordImport;
    }
}
